import React, { useState, useEffect } from 'react';
import { getToken } from './login/loginApi';
import Pagination from './Pagination';
import { fetchAudits } from './Audit/auditApi';
import AuditFixSuggestions from './components/AuditFixSuggestions'; 
import { useNavigate } from 'react-router-dom';

type FixItem = {
  original: string;
  suggestion: string[];
  adopt_suggestions: string;
};
interface Tag {
  id: string;
  name: string;
}

interface User {
  id: string;
  name: string;
  created_at: string;
  updated_at: string;
}

interface Document {
  id: string;
  title: string;
  tags: Tag[];
  storage_key: string;
  created_at: string;
  user: User;
  storage_size: number;
  is_meili: string;
}

interface Pagination {
  pageIndex: number;
  pageSize: number;
  total: number;
}

interface Audit {
  audit_rule_id: string;
  description: string;
}
const apiHost = import.meta.env.VITE_API_HOST || '';
const SelectFile: React.FC = () => {
  const [documents, setDocuments] = useState<Document[]>([]);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [searchTags, setSearchTags] = useState<string>('');
  const [searchTitle, setSearchTitle] = useState<string>('');
  const [pagination, setPagination] = useState<Pagination>({
    pageIndex: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectedFiles, setSelectedFiles] = useState<string>('');
  const [audits, setAudits] = useState<Audit[]>([]);
  const [selectedAuditId, setSelectedAuditId] = useState('');
  const [isLoading, setIsLoading] = useState<boolean>(false); // 添加isLoading状态

  const [showSuggestions, setShowSuggestions] = useState(false);
  const [suggestionsData,setSuggestionsData] = useState<[]>([]);
  const [auditRecordId,setAuditRecordId] =useState<string>('');
  const navigate = useNavigate();

  useEffect(() => {
    // 从 sessionStorage 中读取 selectedFiles
    const storedSelectedFiles = sessionStorage.getItem('selectedFiles') || '';
    setSelectedFiles(storedSelectedFiles);
  }, []);

   // 页面加载时触发接口得到数据
   useEffect(() => {
    const loadAudits = async () => {
      try {
        const res = await fetchAudits(1, 10000, '', '', '');
        if (Array.isArray(res.data)) {
          setAudits(res.data);
          setSelectedAuditId(res.data[0].audit_rule_id)
        } else {
          console.error('Expected an array but received:', res.data);
          setAudits([]);
        }
      } catch (error) {
        console.error('Failed to fetch audits:', error);
        setAudits([]);
      }
    };
    loadAudits();
  }, []);

  const loadDocuments = async (
    tags: string = '',
    title: string = '',
    pageIndex: number = pagination.pageIndex,
    pageSize: number = pagination.pageSize,
  ) => {
    const apiHost = import.meta.env.VITE_API_HOST || '';
    let queryURL = apiHost+`/documents/list/search?page_index=${pageIndex}&page_size=${pageSize}`;
    if (tags) {
      queryURL += `&tags=${encodeURIComponent(tags)}`;
    }
    if (title) {
      queryURL += `&title=${encodeURIComponent(title)}`;
    }

    try {
      const response = await fetch(queryURL, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      });
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const data = await response.json();
      setDocuments(data.data.documents);
      setPagination((prev) => ({ ...prev, total: data.data.total }));
    } catch (error) {
      console.error('Error fetching documents:', error);
    }
  };

  useEffect(() => {
    loadDocuments(
      searchTags,
      searchTitle,
      pagination.pageIndex,
      pagination.pageSize,
    );
  }, [searchTags, searchTitle, pagination.pageIndex, pagination.pageSize]);

  const handleSearch = () => {
    setPagination((prev) => ({ ...prev, pageIndex: 1 }));
    loadDocuments(searchTags, searchTitle, 1, pagination.pageSize);
  };

  const handleClear = () => {
    setSearchTags('');
    setSearchTitle('');
    setPagination((prev) => ({ ...prev, pageIndex: 1 }));
    loadDocuments('', '', 1, pagination.pageSize);
  };

  const handlePreviousPage = () => {
    if (pagination.pageIndex > 1) {
      setPagination((prev) => ({ ...prev, pageIndex: prev.pageIndex - 1 }));
      loadDocuments(searchTags, searchTitle, pagination.pageIndex - 1, pagination.pageSize);
    }
  };

  const handleNextPage = () => {
    if (pagination.pageIndex * pagination.pageSize < pagination.total) {
      setPagination((prev) => ({ ...prev, pageIndex: prev.pageIndex + 1 }));
      loadDocuments(searchTags, searchTitle, pagination.pageIndex + 1, pagination.pageSize);
    }
  };

  const auditDocument = async (storage_key: string,selectedAuditId: string) => {
    console.log(`Auditing document with ID: ${storage_key}`, selectedAuditId);
    // 检查是否已经选择审计规则
    if (!selectedAuditId) {
      alert('请选择审计规则');
      return;
    }
    setIsLoading(true); // 开始审计前设置isLoading为true
    try {
      const response = await fetch(`${apiHost}/documents/auditByGpt`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify({
          storage_key: storage_key,
          audit_rule_id: selectedAuditId,
        }),
      });
  
      if (!response.ok) {
        console.log('审计请求失败');
        return; // 如果响应状态不是OK，退出函数
      }
  
      const auditResponse = await response.json();
      // 确保有有效的auditRecordId才继续执行
      if (!auditResponse || !auditResponse.audit_record_id) {
        console.log('无效的审计响应');
        return; // 如果审计响应无效，退出函数
      }

      const auditRecordId = auditResponse.audit_record_id;
   
  
      // 开始轮询审计状态
      pollAuditStatus(auditRecordId);
    } catch (error) {
      console.error('Error auditing document:', error);
      alert('审计失败');
    } 
  };

// 轮询审计状态函数
const pollAuditStatus = async (auditRecordId: string) => {
  const maxPollAttempts = 16;
  let pollAttempts = 0;

  while (pollAttempts < maxPollAttempts) {
    try {
      const response = await fetch(`${apiHost}/documents/auditByGpt/fix`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify({ audit_record_id: auditRecordId }),
      });

      if (!response.ok) {
        throw new Error('Failed to fetch audit status');
      }

      const data = await response.json();

      if (data.data.result === '已审计,无建议') {
        alert('该记录已审计, 无建议');
        break;
      }

      if (data.data.result === '已审计') {
        setAuditRecordId(data.data.audit_record_id);
        console.log('Audit status:', data.data.audit_record_id);
        console.log(auditRecordId)
        setSuggestionsData(data.data.suggestions);
        setShowSuggestions(true);
        setIsLoading(false); // 审计完成后设置isLoading为false
        

        const additionalInfoResponse  = await fetch(`${apiHost}/documents/auditByGpt/storageKey/list`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${getToken()}`,
          },
          body: JSON.stringify({ audit_record_id: data.data.audit_record_id, storage_key: data.data.storage_key,}),
        });
        
        const additionalInfoData = await additionalInfoResponse.json();
        setSuggestionsData(additionalInfoData.data.suggestions);
        setShowSuggestions(true);
      
        

        break;
      }

      await new Promise((resolve) => setTimeout(resolve, 2000));
    } catch (error) {
      console.error('轮询过程中发生错误:', error);
      setIsLoading(false);
      break;
    } finally {
      pollAttempts += 1;
    }

    if (pollAttempts === maxPollAttempts) {
      console.log('达到最大轮询次数，退出轮询');
      alert('系统繁忙，请稍后再试');
      setIsLoading(false); // 审计完成后设置isLoading为false
      
    }
  }
};

const handleSelectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
  // 获取选中项的值
  const selectedValue = event.target.value;
    // 打印选中项的值和label
  console.log('选中的值:', selectedValue);

  setSelectedAuditId(selectedValue);
};

const handleAudit = async () => {
  if (selectedIds.length === 1) {
    // 通过选中的ID找到相应的文档对象
    const selectedDocument = documents.find(doc => doc.id === selectedIds[0]);
    if (selectedDocument) {
      // 使用文档的 storage_key 调用审计接口
      setSelectedFiles(selectedDocument.storage_key);;
      await auditDocument(selectedDocument.storage_key,selectedAuditId);
    } else {
      alert('未找到选中的文件');
    }
  } else {
    alert('请选择一个文件进行审计');
  }
};

// 提交数据的函数
const submitSuggestions = (suggestions: FixItem[], storageKey: string) => {
  if (!auditRecordId){
    alert('审计流程出错');
    return;
  }
  console.log("携带数据跳转到aiEdit:", suggestions, storageKey);
  // 携带建议数据跳转到aiEdit, aiEdit再触发接口获取原文件的原文
  navigate('/aiEditCustom', { state: { suggestions, storageKey } });

  
  const fixItems = suggestions.map(item => ({
    original: item.original,
    adoption: item.adopt_suggestions 
  }));

  try {
    fetch(`${apiHost}/documents/auditByGpt/fix/save`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getToken()}`,
      },
      body: JSON.stringify({
        audit_record_id: auditRecordId,
        fix_item: fixItems, 
      }),
    });
  } catch (error) {
    console.error('Error fetching documents:', error);
  }
};

  return (
    <div>
        {isLoading && ( // 如果isLoading为true，则显示全屏加载遮罩
        <div className="fixed top-0 left-0 z-50 flex h-full w-full items-center justify-center bg-black bg-opacity-50">
          <div className="rounded-lg bg-white p-4 shadow-lg">
            <p>正在加载中，请稍候...</p>
          </div>
        </div>
      )}
      <div className="mb-5 items-center gap-2">
        <input
          type="text"
          value={searchTags}
          onChange={(e) => setSearchTags(e.target.value)}
          placeholder="所属标签"
          className="flex-grow rounded-lg border border-gray-300 p-2"
        />
        <input
          type="text"
          value={searchTitle}
          onChange={(e) => setSearchTitle(e.target.value)}
          placeholder="标题查询"
          className="ml-2 flex-grow rounded-lg border border-gray-300 p-2"
        />
        <button
          onClick={handleSearch}
          className="ml-2 mr-2 cursor-pointer rounded-lg bg-blue-500 p-2 text-white hover:bg-blue-700"
        >
          查询
        </button>
        <button
          onClick={handleClear}
          className="cursor-pointer rounded-lg bg-gray-600 p-2 text-white hover:bg-gray-700"
        >
          清空
        </button>
      </div>
      {/* 文档列表 */}
      <table className="min-w-full table-fixed border-collapse border">
        <thead className="bg-gray-200">
          <tr>
            <th className="border p-2">文件名称</th>
            <th className="border p-2">作者</th>
            <th className="border p-2">上传时间</th>
            <th className="border p-2">文件大小</th>
            <th className="border p-2">所属标签</th>
            <th className="border p-2">查看文件</th>
            <th className="border p-2">选择</th>
          </tr>
        </thead>
        <tbody>
          {documents.map((doc) => (
            <tr key={doc.id} className="hover:bg-gray-100">
              <td className="border p-2">{doc.storage_key}</td>
              <td className="border p-2">{doc.user.name}</td>
              <td className="border p-2">
                {new Date(doc.created_at).toLocaleDateString()}
              </td>
              <td className="border p-2">{doc.storage_size} bytes</td>
              <td className="border p-2">
                {doc.tags.map((tag, index) => (
                  <span key={tag.id}>
                    {tag.name}
                    {index < doc.tags.length - 1 ? ', ' : ''}
                  </span>
                ))}
              </td>
              
              <td className="border p-2 text-center">
              <a href={ apiHost+`/documents/pre/preview/${doc.storage_key}`} target="_blank" >查看</a>
            </td>
            <td className="border p-2 text-center">
                <input
                  type="checkbox"
                  checked={selectedIds.includes(doc.id)}
                  onChange={() => {
                    // 当doc.is_meili为'2'或'6'时，才处理勾选逻辑
                    if (doc.is_meili === '2' || doc.is_meili === '6') {
                      setSelectedIds((prev) =>
                        prev.includes(doc.id)
                          ? prev.filter((id) => id !== doc.id) // 如果已选中，则移除
                          : [...prev, doc.id], // 如果未选中，则添加
                      );
                    }
                  }}
                  disabled={!(doc.is_meili === '2' || doc.is_meili === '6')}
                />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {/* 分页控件 */}
      <Pagination
        pageIndex={pagination.pageIndex}
        total={pagination.total}
        pageSize={pagination.pageSize}
        handlePreviousPage={handlePreviousPage}
        handleNextPage={handleNextPage}
      />
      <button
        onClick={() => {
          const selectedFiles = documents
            .filter((doc) => selectedIds.includes(doc.id))
            .map((doc) => doc.storage_key)
            .join(', ');

               // 将选中的文件字符串存储到 SessionStorage 中
          sessionStorage.setItem('selectedFiles', selectedFiles);
          setSelectedFiles(selectedFiles);
          alert('选中的文件是： '+selectedFiles);
        }}
        className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-700"
      >
        确定选中的文件
      </button>
        {/* 下拉框 */}
        <select className="mt-4 rounded-md ml-4 bg-white border px-4 py-2 hover:border-gray-400" onChange={handleSelectChange}>
        {(audits|| []).map((audit) => (
          <option value={audit.audit_rule_id} 
          key = {audit.audit_rule_id}
          title={audit.description}
           >
            {audit.description}
          </option>
        ))}
       </select>

      <button
        onClick={handleAudit}
        disabled={selectedIds.length !== 1}
        className="mt-4 rounded-md ml-4 bg-purple-500 px-4 py-2 text-white hover:bg-purple-700 disabled:bg-purple-300"
      >
        GPT审计文件
      </button>
      {showSuggestions && <AuditFixSuggestions suggestions={suggestionsData}  onSubmit={submitSuggestions}   storageKey={selectedFiles} />}
      <div className="mt-4">
        <h2>选中的文件内容：</h2>
        <p>{selectedFiles}</p>
      </div>
    </div>
  );
};

export default SelectFile;